/*
 * Created on Jan 8, 2009
 */
package ak.salmon;

import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ak.salmon.markup.DrawingPalette;
import ak.salmon.markup.SvgDrawingPalette;
import ak.salmon.model.DrawingElement;
import ak.salmon.model.Node;
import ak.salmon.model.NodeContent;

public class SalmonChartBuilder {

    private final SalmonLayoutEngineFactory lef;

    public SalmonChartBuilder(SalmonLayoutEngineFactory lef) {
        this.lef = lef;
    }

    public String render(List<NodeContent> nodes, String engine) {
        DrawingElement head = build(nodes, engine);
        return render(head);
    }

    private String render(DrawingElement head) {
        DrawingPalette palette = new SvgDrawingPalette();

        palette.begin();
        head.plan();
        head.position(new Point(0, 0));
        head.draw(palette);
        palette.end();

        return palette.toString();
    }

    private DrawingElement build(List<NodeContent> nodes, String engine) {

        // build reference map
        Map<Object, List<Node>> childMap = new HashMap<Object, List<Node>>();

        Node head = null;

        for (NodeContent info : nodes) {
            Node node = new Node(info);

            if (info.getParentId() == null) {
                head = node;
            } else {
                List<Node> children = childMap.get(info.getParentId());
                if (children == null) {
                    children = new ArrayList<Node>();
                    childMap.put(info.getParentId(), children);
                }
                children.add(node);
            }
        }

        SalmonLayoutEngine le = lef.get(engine);
        return le.setup(head, childMap);
    }
}
